<?php
defined('_JEXEC') or die('Restricted access');
JToolBarHelper::title(JText::_('NS Pro Subscribers'), 'user.png');

$jversion = new JVersion();
$j15 = ($jversion->RELEASE == '1.5');
//$j16 = ($jversion->RELEASE == '1.6');

jimport('joomla.application.component.helper');
$params = JComponentHelper::getParams( 'com_nspro' );
if ($j15 == true) {
  $component = JComponentHelper::getComponent( 'com_nspro' );
  $params = new JParameter( $component->params );
}

$import_delim = $params->get('import_delimiter', ';');
$import_ns_delim = $params->get('import_ns_delimiter', '0');
$ns_ldelim = '(';
$ns_rdelim = ')';
if ($import_ns_delim == '1') {
  $ns_ldelim = '&lt;';
  $ns_rdelim = '&gt;';
}
else if ($import_ns_delim == '2') {
  $ns_ldelim = '[';
  $ns_rdelim = ']';
}
else if ($import_ns_delim == '3') {
  $ns_ldelim = '{';
  $ns_rdelim = '}';
}

function FilterSearch($sstring) {
  $result = $sstring;
  if ((isset($_POST["searchsubscribers"])) && (isset($_POST["subsearchkey"])) && ($_POST["subsearchkey"] !== '')) {
    $myspan = '<span style="background-color: #ff0;">' . $_POST["subsearchkey"] . '</span>';
    $result = JString::str_ireplace($_POST["subsearchkey"], $myspan, $sstring);
  }
  return $result;
}

$db =& JFactory::getDBO();
$db->setQuery('SELECT `id`, `lname` FROM `#__nspro_lists`');
$lists = $db->loadObjectList();

$db->setQuery('SELECT * FROM `#__nspro_fields` WHERE `show_backend` = true ORDER BY `ordering`');
$afields = $db->loadObjectList();
$fcount = 9 + count($afields);

$db->setQuery('SELECT COUNT(*) FROM `#__nspro_subs`');
$totalcount = $db->loadResult();
$db->setQuery('SELECT COUNT(*) FROM `#__nspro_subs` WHERE `confirmed` = true');
$confirmedcount = $db->loadResult();
$db->setQuery('SELECT MIN(`datetime`) FROM `#__nspro_subs`');
$firstdate = $db->loadResult();
$db->setQuery('SELECT MAX(`datetime`) FROM `#__nspro_subs`');
$lastdate = $db->loadResult();

$subids = '';
foreach ($this->subs as $sub) {
  if ($subids == '') {
    $subids = "'" . $sub->id . "'";
  }
  else {
    $subids .= ", '" . $sub->id . "'";
  }
}
$query = 'SELECT * FROM `#__nspro_field_values` WHERE `subscriber_id` IN ('.$subids.')';
$db->setQuery($query);
$fieldValues = $db->loadObjectList();

?>
<script type="text/javascript"><!--

  function submitForm() {
    document.adminForm.submit();
  }

--></script>
<div id="statcell" style="padding-bottom: 5px;">
    <table class="adminlist">
    <thead>
        <tr>
            <th>
                <?php echo JText::_('Subscription Count'); ?>
            </th>
            <th>
                <?php echo JText::_( 'Confirmed Subscriptions' ); ?>
            </th>
            <th>
                <?php echo JText::_( 'First Subscription' ); ?>
            </th>
            <th>
                <?php echo JText::_( 'Last Subscription' ); ?>
            </th>
            <th>
                <?php echo JText::_( 'Subscriptions per day' ); ?>
            </th>
        </tr>
    </thead>
    <tbody>
      <tr>
        <td align="center">
          <?php
            print $totalcount;
          ?>
        </td>
        <td align="center">
          <?php
            $actives = $confirmedcount;
            if ($totalcount > 0) {
              $cpt = ($confirmedcount * 100) / $totalcount;
              print $confirmedcount . ' (';
              printf("%01.2f", $cpt);
              print ' %)';
            }
            else {
              print $confirmedcount;
            }
          ?>
        </td>
        <td align="center">
          <?php
            if ($totalcount > 0) {
              print date('r', strtotime($firstdate));
            }
            else {
              print JText::_('N/A');
            }
          ?>
        </td>
        <td align="center">
          <?php
            if ($totalcount > 0) {
              print date('r', strtotime($lastdate));
            }
            else {
              print JText::_('N/A');
            }
          ?>
        </td>
        <td align="center">
          <?php
            if ($totalcount > 0) {

              $firstDate = strtotime($firstdate);
              $lastDate = strtotime($lastdate);
              $diff = intval(($lastDate-$firstDate) / 86400) + 1;

              if ($diff == 0) {
                $diff = 1;
              }
              $spd  = $totalcount / $diff;
              printf("%01.2f", $spd);
            }
            else {
              print JText::_('N/A');
            }
          ?>
        </td>
      </tr>
      </tbody>
    </table>
</div>
<form id="adminForm" action="<?php echo JRoute::_( 'index.php' );?>"  method="post" name="adminForm">
<div id="editcell">
    <table style="padding-bottom: 5px; width: 100%;">
    <tr>
    <td align="left">
      <?php
        if ((isset($_POST["searchsubscribers"])) && (isset($_POST["subsearchkey"])) && ($_POST["subsearchkey"] !== '')) {
        ?>
          <div id="search_parent">
            <div id="search_fields">
              <input type="hidden" name="searchsubscribers" value="Search"/>
              <input type="hidden" name="subsearchkey" value="<?php print $_POST["subsearchkey"]; ?>"/>
            </div>
          </div>
          <script type="text/javascript"><!--

            function removeSearch() {
              var d1=document.getElementById("search_parent");
              var d2=document.getElementById("search_fields");
              d1.removeChild(d2);
              document.adminForm.submit();
            }

          --></script>
          Searching: <span style="color: #f00;"><?php print $_POST["subsearchkey"]; ?></span>&nbsp;<a href="#" onClick="removeSearch()"><?php print JText::_('Clear Searched Text') ?></a>
        <?php
        }
        else { ?>
      <input type="text" name="subsearchkey"/>
      <input type="hidden" name="new_search" value="yes"/>
      <input type="submit" class="button" name="searchsubscribers" value="<?php print JText::_('Search') ?>"/>
        <?php } ?>
    </td>
    <td align="right"><?php

      $db->setQuery('SELECT `id`, `lname` FROM `#__nspro_lists`');
      $mlist = $db->loadObjectList();

      $first_element = array();
      $firstEl = new stdClass();
      $firstEl->id = -1;
      $firstEl->lname = JText::_('No List');
      $first_element[] = $firstEl;
      $mlist = array_merge($first_element, $mlist);
      $first_element = array();
      $firstEl = new stdClass();
      $firstEl->id = 0;
      $firstEl->lname = JText::_('All Lists');
      $first_element[] = $firstEl;
      $mlist = array_merge($first_element, $mlist);
      print JHTML::_('select.genericlist',  $mlist , 'select_list', 'onChange="submitForm();"', 'id', 'lname', $this->filter_subs);

    ?></td></tr>
    </table>
    <table class="adminlist">
    <thead>
        <tr>
            <th width="5">
                <?php echo JHTML::_( 'grid.sort', JText::_( 'ID' ), 'id', $this->olists['order_Dir'], $this->olists['order']); ?>
            </th>
            <th width="20">
                <input type="checkbox" name="toggle" value="" onclick="checkAll(<?php echo count( $this->subs ); ?>);" />
            </th>
            <th class="title">
                <?php echo JHTML::_( 'grid.sort', JText::_('Name'), 'name', $this->olists['order_Dir'], $this->olists['order']); ?>
            </th>
            <th class="email">
                <?php echo JHTML::_( 'grid.sort', JText::_('Email'), 'email', $this->olists['order_Dir'], $this->olists['order']); ?>
            </th>
            <th class="datetime" align="center">
                <?php echo JHTML::_( 'grid.sort', JText::_('Date and Time'), 'datetime', $this->olists['order_Dir'], $this->olists['order']); ?>
            </th>
            <th width="80">
                <?php echo JHTML::_( 'grid.sort', JText::_('Confirmed'), 'confirmed', $this->olists['order_Dir'], $this->olists['order']); ?>
            </th>
            <th>
                <?php echo JText::_( 'Mailing Lists' ); ?>
            </th>
            <th width="30%" class="notes">
                <?php echo JText::_( 'Notes' ); ?>
            </th>
            <?php
              foreach ($afields as $af) {
                print '<th>';
                print JText::_($af->name);
                print '</th>';
              }
            ?>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <td colspan="<?php print $fcount; ?>">
                <?php
                  print $this->pagination->getListFooter();
                ?>
            </td>
        </tr>
    </tfoot>
    <tbody>
    <?php
    $k = 0;
    for ($i=0, $n=count( $this->subs ); $i < $n; $i++)
    {
        $row = &$this->subs[$i];
        $row->checked_out = false;
        $checked    = JHTML::_('grid.checkedout', $row, $i );
        $link       = JRoute::_( 'index.php?option=com_nspro&controller=nspro&task=edit&cid[]='. $row->id );
        $conflink   = JRoute::_( 'index.php?option=com_nspro&controller=nspro&task=qconfirm&cid[]='. $row->id );
        $uconflink  = JRoute::_( 'index.php?option=com_nspro&controller=nspro&task=quconfirm&cid[]='. $row->id );

        ?>
        <tr class="<?php echo "row$k"; ?>">
            <td>
                <?php echo $row->id; ?>
            </td>
            <td>
                <?php echo $checked; ?>
            </td>
            <td>
                <a href="<?php echo $link; ?>"><?php echo FilterSearch($row->name); ?></a>
            </td>
            <td>
                <?php echo FilterSearch($row->email); ?>
            </td>
            <td align="center">
                <?php print date('r', strtotime($row->datetime)); ?>
            </td>
            <td align="center">
              <?php
              if ($row->confirmed) {
                print '<a href="'.$uconflink.'">'.JText::_('Yes').'</a>';
              }
              else {
                print '<a href="'.$conflink.'">'.JText::_('No').'</a>';
              }
              ?>
            </td>
            <td align="center">
               <?php
                 $myLName = '';
                 $mySubLists = explode(',', $row->mailing_lists);
                 for ($j = 0; $j < count($lists); $j++) {
                   $arow = $lists[$j];
                   foreach ($mySubLists as $myListID) {
                     if ($arow->id == $myListID) {
                       if ($myLName == '') {
                         $myLName = $arow->lname;
                       }
                       else {
                         $myLName = $myLName . ', ' . $arow->lname;
                       }
                       break;
                     }
                   }
                 }

                 if ($myLName == '') {
                   $myLName = JText::_('No List Assigned');
                 }

                 print $myLName;

               ?>
            </td>
            <td>
                <?php echo $row->notes; ?>
            </td>
            <?php
              foreach ($afields as $af) {
                print '<td>';
                $value = '';
                foreach($fieldValues as $fv) {
                  if (($fv->subscriber_id == $row->id) && ($fv->field_id == $af->id)) {
                    $value = $fv->value;
                    break;
                  }
                }

                if ($af->fieldtype == '2') { // boolean
                  if ($value == true) {
                    print JText::_('Yes');
                  }
                  else {
                    print JText::_('No');
                  }
                }
                else if (($af->fieldtype == '0') || ($af->fieldtype == '1')) {
                  if (strlen(htmlentities($value)) > 100) {
                    print JString::substr(htmlentities($value), 0, 100) . '...';
                  }
                  else {
                    print htmlentities($value);
                  }
                }
                else {
                  print $value;
                }
                print '</td>';
              }
            ?>
        </tr>
        <?php
        $k = 1 - $k;
    }
    ?>
      </tbody>
    </table>
</div>

<input type="hidden" name="option" value="com_nspro" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="boxchecked" value="0" />
<input type="hidden" name="controller" value="nspro" />
<input type="hidden" name="view" value="subscribers" />
<input type="hidden" name="filter_order" value="<?php echo $this->olists['order']; ?>" />
<input type="hidden" name="filter_order_Dir" value="<?php echo $this->olists['order_Dir']; ?>" />
</form>
<br /><br />

<?php if ($j15 == true) { ?>
  <div class="icon-48-cpanel header">NS Pro Import / Export</div>
<?php } else { ?>
  <div class="pagetitle icon-48-config"><h2>NS Pro Import / Export</h2></div>
<?php } ?>

<div id="nspro_tools">
<?php if ($j15 == true) { ?>

<table class="toolbar nspro">
<tr>
<td id="toolbar-archive">
<a class="toolbar" onclick="javascript:submitbutton('exporttxt');" href="#">
<span class="icon-32-archive" title="Export Txt"> </span>
Export Text File (*.txt)
</a>
</td>
<td id="toolbar-archive">
<a class="toolbar" onclick="javascript:submitbutton('exportcsv');" href="#">
<span class="icon-32-archive" title="Export Csv"> </span>
Export Excel File (*.csv)
</a>
</td>
<td id="toolbar-archive">
<a class="toolbar" onclick="javascript:submitbutton('exportns');" href="#">
<span class="icon-32-archive" title="Export Newsletter Subscriber List File"> </span>
Export Newsletter Subscriber List File
</a>
</td>
<td id="toolbar-archive">
<a class="toolbar" onclick="javascript:submitbutton('exportxml');" href="#">
<span class="icon-32-archive" title="Export XML"> </span>
Export XML
</a>
</td>
<td id="toolbar-unarchive">
<a class="toolbar" onclick="javascript:submitbutton('importFromJoomla');" href="#">
<span class="icon-32-unarchive" title="Import From Joomla Users"> </span>
Import From Joomla Users
</a>
</td></tr></table>
<?php } else { ?>
<div class="toolbar-list" id="toolbar">
<ul>

<li class="button" id="toolbar-new">
<a href="#" onclick="javascript:Joomla.submitbutton('exporttxt')" class="toolbar">
<span class="icon-32-archive">
</span>
Export Text File (*.txt)
</a>
</li>

<li class="button" id="toolbar-new">
<a href="#" onclick="javascript:Joomla.submitbutton('exportcsv')" class="toolbar">
<span class="icon-32-archive">
</span>
Export Excel File (*.csv)
</a>
</li>

<li class="button" id="toolbar-new">
<a href="#" onclick="javascript:Joomla.submitbutton('exportns')" class="toolbar">
<span class="icon-32-archive">
</span>
Export Newsletter Subscriber List File
</a>
</li>

<li class="button" id="toolbar-new">
<a href="#" onclick="javascript:Joomla.submitbutton('exportxml')" class="toolbar">
<span class="icon-32-archive">
</span>
Export XML
</a>
</li>

<li class="divider">
</li>

<li class="button" id="toolbar-new">
<a href="#" onclick="javascript:Joomla.submitbutton('importFromJoomla')" class="toolbar">
<span class="icon-32-unarchive">
</span>
Import from Joomla Users
</a>
</li>

</ul>
<div class="clr"></div>
</div>
<?php } ?>
</div>
<br />

<form enctype="multipart/form-data" action="index.php" method="POST" name="fileform">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />

<table class="adminform">
<tr><th colspan="2"><?php print JText::_('Import from Text/Excel File') ?></th></tr>
<tr><td width="150"><?php print JText::_('Import File:') ?></td><td><input class="input_box" name="uploadedfile" type="file" size="57"/> <input type="submit" value="<?php print JText::_('Upload File & Import') ?>"/></td></tr>
<tr><td><?php print JText::_('Import Source/Type');?></td>
<td><input type="radio" name="inputtype" value="0" checked/>Newsletter Subscriber List File&nbsp;&nbsp;<i><a href="../index.php?option=com_nspro&task=import_example&type=ns" target="_blank"><?php print JText::_('Click for Import Example')?></a></i>
<br/><input type="radio" name="inputtype" value="1"/>Text File separated by Import Delimiter (see parameters)&nbsp;&nbsp;<i><a href="../index.php?option=com_nspro&task=import_example&type=txt" target="_blank"><?php print JText::_('Click for Import Example')?></a></i>
<br/><input type="radio" name="inputtype" value="2"/>Excel File separated by Import Delimiter (see parameters)&nbsp;&nbsp;<i><a href="../index.php?option=com_nspro&task=import_example&type=csv" target="_blank"><?php print JText::_('Click for Import Example')?></a></i></td></tr>
</table>

<input type="hidden" name="option" value="com_nspro" />
<input type="hidden" name="task" value="importtxt" />
<input type="hidden" name="boxchecked" value="0" />
<input type="hidden" name="controller" value="nspro" />
</form>
<center><small><i>NS Pro by <a href="http://www.mavrosxristoforos.com/">Mavrosxristoforos.com</a> Copyright 2009-2011</i></small></center>
